<?php

include '../vendor/autoload.php';

use EthTool\Callback;
use EthTool\Credential;

use Web3\Utils;

use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;

date_default_timezone_set('PRC');


$web3 = new Web3(new HttpProvider(new HttpRequestManager('https://data-seed-prebsc-1-s1.binance.org:8545', 5)));

$cb = new Callback();
// ---转账
$credential = Credential::fromKey('7487e9e7e6d4d574d5a0f5161ff5abe5e104670aea08621d9af3839265b5632a');

echo '转账' . PHP_EOL;
$web3->eth->getTransactionCount($credential->getAddress(),'latest',$cb); 
$nonce =  $cb->result;

$raw = [
    'nonce' => Utils::toHex($nonce,true),
    'gasPrice' => '0x' . Utils::toWei('20','gwei')->toHex(),
    'gasLimit' => '0x76c0',
    'to' => '0xdb8b681c5Cc50Af19eC406b55301dD3bB0dFA574',
    'value' => '0x'.Utils::toWei('0.01','ether')->toHex(),
    'data' => '0x' . bin2hex('hello'),
    'chainId' => 97
];
$req = $credential->signTransaction($raw);

$web3->eth->sendRawTransaction($req,$cb);
echo 'tx hash: ' . $cb->result . PHP_EOL;
waitForReceipt($web3,$cb->result);

$web3->eth->getBalance('0xdb8b681c5Cc50Af19eC406b55301dD3bB0dFA574',$cb);
echo 'wallet balance: ' . $cb->result . PHP_EOL;

function waitForReceipt($web3,$txhash,$timeout=60,$interval=1){
	$cb = new Callback;
	$t0 = time();
	while(true){
		$web3->eth->getTransactionReceipt($txhash,$cb);       
		if($cb->result) break;
		$t1 = time();
		if(($t1 - $t0) > $timeout) break;
		sleep($interval);  
	}
	return $cb->result;
}